<?php
class Pageley_Messaging_Mail_Provider implements Pageley_Messaging_Provider {
    public function sendMessage($message) {
        $primaryRecipients = $this->recipientsAsString(
            $message->getRecipients(Pageley_Messaging_RecipientType::$PRIMARY));
        $secondaryRecipients = $this->recipientsAsString(
            $message->getRecipients(Pageley_Messaging_RecipientType::$SECONDARY));
        $anonymousRecipients = $this->recipientsAsString(
            $message->getRecipients(Pageley_Messaging_RecipientType::$ANONYMOUS));
        
        $subject = $message->getSubject();
        $content = wordwrap($message->getContent(), 70);
        $sender = $message->getSender();
        $contentType = $message->getContentType();
        $headers = 
            "MIME-Version: 1.0\n" .
            "Content-Type: " . $contentType . "; charset=UTF-8\n" .
            ($sender !== null ? "From: " . $sender . "\n" : "") .
            ($secondaryRecipients !== null ? "Cc: " . $secondaryRecipients . "\n" : "") .
            ($anonymousRecipients !== null ? "Bcc: " . $anonymousRecipients . "\n" : "") .
            "X-Mailer: PHP/" . phpversion() . "\n";
            
        return mail($primaryRecipients, $subject, $content, $headers);
    }
    
    private function recipientsAsString($recipients) {
        $string = null;
        foreach($recipients as $recipient) {
            if($string !== null) {
                $string .= ", ";
            } else {
                $string = "";
            }
            $string .= $recipient;
        }
        return $string;
    }
}